package com.ruoyi.tzzl.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.tzzl.domain.*;
import com.ruoyi.tzzl.domain.vo.QueryVo;
import com.ruoyi.tzzl.mapper.WzProgramUserMapper;
import com.ruoyi.tzzl.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.US_ASCII;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 小程序用户Service业务层处理
 * @author by caoyong
 * @date 2022/11/7
 **/

@Service
public class WzProgramUserServiceImpl extends ServiceImpl<WzProgramUserMapper, WzProgramUser> implements IWzProgramUserService {

    @Autowired
    private WzProgramUserMapper wzProgramUserMapper;

    @Autowired
    private IWzCertificationService wzCertificationService;

    @Autowired
    private IWzPhotoAlbumService wzPhotoAlbumService;

    @Autowired
    private IWzUserDetailsService wzUserDetailsService;

    @Autowired
    private IWzDynamicService wzDynamicService;

    @Autowired
    private IWzBalanceChangeRecordService wzBalanceChangeRecordService;

    @Autowired
    private IWzOrderService wzOrderService;

    @Autowired
    private IWzMatchmakerApplyService wzMatchmakerApplyService;

    @Autowired
    private IWzWithdrawalRecordService wzWithdrawalRecordService;

    @Autowired
    private IWzCommentsService wzCommentsService;
    @Autowired
    private IWzFocusonService wzFocusonService;
    @Autowired
    private IWzPayOrderRecordService wzPayOrderRecordService;
    @Autowired
    private ISysDictTypeService dictTypeService;


    @Autowired
    private RedisCache redisCache;

    /**
     * 查询小程序用户列表
     *
     * @param wzProgramUser 小程序用户
     * @return 小程序用户集合
     */
    @Override
    public List<WzProgramUser> selectWzProgramUserList(WzProgramUser wzProgramUser) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        //昵称
        if (ObjectUtils.isNotEmpty(wzProgramUser.getUserName())){
            lqw.eq(WzProgramUser::getUserName,wzProgramUser.getUserName());
        }
        //性别
        if (ObjectUtils.isNotEmpty(wzProgramUser.getSex())){
            lqw.eq(WzProgramUser::getSex,wzProgramUser.getSex());
        }
        //会员等级
        if (ObjectUtils.isNotEmpty(wzProgramUser.getUserLevel())){
            lqw.eq(WzProgramUser::getUserLevel,wzProgramUser.getUserLevel());
        }
        //注册时间
        if (ObjectUtils.isNotEmpty(wzProgramUser.getStartTime())){
           lqw.between(WzProgramUser::getCreateTime,wzProgramUser.getStartTime(),wzProgramUser.getEndTime());
        }
        //用户身份
        if (ObjectUtils.isNotEmpty(wzProgramUser.getRole())){
            lqw.eq(WzProgramUser::getRole,wzProgramUser.getRole());
        }
        //年龄范围筛选
        if (ObjectUtils.isNotEmpty(wzProgramUser.getAgeRange())){
            switch (wzProgramUser.getAgeRange()){
                case "1":
                    lqw.in(WzProgramUser::getAge,18,19,20,21,22);
                    break;
                case "2":
                    lqw.in(WzProgramUser::getAge,23,24,25,26,27);
                    break;
                case "3":
                    lqw.in(WzProgramUser::getAge,28,29,30,31,32);
                    break;
                case "4":
                    lqw.in(WzProgramUser::getAge,33,34,35,36,37);
                    break;
                case "5":
                    lqw.in(WzProgramUser::getAge,38,39,40,41,42);
                    break;
                case "6":
                    lqw.in(WzProgramUser::getAge,43,44,45,46,47);
                    break;
                case "7":
                    lqw.in(WzProgramUser::getAge, 48,49,50,51,52);
                    break;
                case "8":
                    lqw.in(WzProgramUser::getAge,53,54,55,56,57,58,59,60);
                    break;
            }
        }
        List<WzProgramUser> userList =this.list(lqw);
        if (ObjectUtils.isNotEmpty(userList)){
            for (int i = 0; i < userList.size(); i++) {
                if (ObjectUtils.isNotEmpty(userList.get(i).getMatchmakerId())){
                    userList.get(i).setMatchmakerUser(this.getById(userList.get(i).getMatchmakerId()));
                    userList.get(i).setMembersNumber(this.getByMatchmakerId(userList.get(i).getMatchmakerId()).size()== 0 ? 0 :this.getByMatchmakerId(userList.get(i).getMatchmakerId()).size() -1);
                }
                userList.get(i).setTheCumulative(wzBalanceChangeRecordService.theCumulative(userList.get(i).getId()));
            }
        }
        return userList;
    }

    @Override
    public WzProgramUser getByName(String name) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getUserName,name);
        return this.getOne(lqw);
    }

    /**
     * 查询用户详情
     * */
    @Override
    public WzProgramUser userDetails(Long id) {
        return wzProgramUserMapper.detailedProgramUser(id);
    }

    /**
     * 查询用户信息
     * 旗下会员人数
     * 完成邀约订单数量
     *
     * @param id
     */
    @Override
    public WzProgramUser details(Long id) {
        WzProgramUser user =this.getById(id);
        user.setInvitationOrders(wzOrderService.invitationOrders(id)) ; //完成邀约订单次数
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getMatchmakerId,id);
        lqw.eq(WzProgramUser::getRole,"2");
        user.setMembership(this.list(lqw).size());
        return user;
    }

    /**
     * 查询平台信息
     */
    @Override
    public WzProgramUser platform() {
        List<SysDictData> data = dictTypeService.selectDictDataByType("platform_config");
        WzProgramUser user =new WzProgramUser();
        user.setUserName("平台");
        user.setPhone(Long.parseLong(data.get(0).getDictValue()));
        user.setLocation(data.get(1).getDictValue());
        user.setInvitationOrders(wzOrderService.invitationOrders(null)) ; //完成邀约订单次数
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getMatchmakerId,null);
        lqw.eq(WzProgramUser::getRole,"2");
        user.setMembership(this.list(lqw).size());
        return user;
    }

    /**
     * 查询用户资料详情
     *
     * @param id
     */
    @Override
    public Map<String, Object> informationDetails(Long id) {
        Map<String,Object> map =new HashMap<>();
        //用户详情
       WzProgramUser wzProgramUser = wzProgramUserMapper.detailedProgramUser(id);
        map.put("userDetails",wzProgramUser);
        //认证资料
        List<WzCertification> list = wzCertificationService.getByWid(id);
        map.put("WzCertificationList",list);
        //动态圈子
       List<WzDynamic> dynamicList = wzDynamicService.getByWid(id,null,null,null);
       map.put("dynamicList",dynamicList);
       //相册
       List<WzPhotoAlbum> photoAlbumList = wzPhotoAlbumService.getByWid(id);
       map.put("photoAlbumList",photoAlbumList);
        return map;
    }

    /**
     * 修改用户个人资料
     *
     * @param wzUserDetails
     */
    @Override
    public boolean updateDetails(WzUserDetails wzUserDetails) {
        WzProgramUser user =this.getById(wzUserDetails.getWid()); //用户信息
        //形象照||昵称
        if (ObjectUtils.isNotEmpty(wzUserDetails.getSex()) || ObjectUtils.isNotEmpty(wzUserDetails.getPhoto())  || ObjectUtils.isNotEmpty(wzUserDetails.getUserName()) ){
            if (ObjectUtils.isNotEmpty(wzUserDetails.getPhoto())){
                user.setAvatarurl(wzUserDetails.getPhoto()); //头像
            }
            if (ObjectUtils.isNotEmpty(wzUserDetails.getUserName())){ //昵称
                user.setUserName(wzUserDetails.getUserName());
            }
            if (ObjectUtils.isNotEmpty(wzUserDetails.getSex())){
                user.setSex(wzUserDetails.getSex());
            }
            this.updateById(user);
        }

        //生活照
        if (ObjectUtils.isNotEmpty(wzUserDetails.getPhotoAlbumUrlList())){
            WzPhotoAlbum wzPhotoAlbum =new WzPhotoAlbum();
            List<WzPhotoAlbum> list =new ArrayList<>();
            for (int i = 0; i < wzUserDetails.getPhotoAlbumUrlList().size(); i++) {
                wzPhotoAlbum.setWid(wzUserDetails.getWid());
                wzPhotoAlbum.setPhotoUrl(wzUserDetails.getPhotoAlbumUrlList().get(i));
                wzPhotoAlbum.setCreateTime(new Date());
                list.add(wzPhotoAlbum);
            }
                wzPhotoAlbumService.saveBatch(list);
        }
        WzUserDetails wzUserDetails1 = wzUserDetailsService.selectWzUserDetailsById(wzUserDetails.getWid());

        if (ObjectUtils.isNotEmpty(wzUserDetails1)){
            Long id =wzUserDetails1.getId();
            String yourself =wzUserDetails1.getIntroduce(); //自我介绍
            String zfbAccount =wzUserDetails1.getZfbAccount(); //支付宝账号
            String zfbName =wzUserDetails1.getZfbName(); //支付宝实名姓名
            BeanUtils.copyProperties(wzUserDetails,wzUserDetails1);
            wzUserDetails1.setId(id);
            wzUserDetails1.setIntroduce(yourself);
            wzUserDetails1.setZfbAccount(zfbAccount);
            wzUserDetails1.setZfbName(zfbName);
            //出生年月
            if (ObjectUtils.isNotEmpty(wzUserDetails1.getDateOfBirth())){
                int age = DateUtils.getAge(wzUserDetails1.getDateOfBirth());
                user.setAge(Long.valueOf(age));
                this.updateById(user);
            }
            //主页照片
            if (ObjectUtils.isNotEmpty(wzUserDetails.getHomepagePicture())){
               wzUserDetails1.setHomepagePicture(wzUserDetails.getHomepagePicture());
            }
            return wzUserDetailsService.updateById(wzUserDetails1);
        }else{
            WzUserDetails userDetails =new WzUserDetails();
            BeanUtils.copyProperties(wzUserDetails,userDetails);
            return wzUserDetailsService.save(userDetails);
        }

    }

    /**
     * 修改用户信息(后台)
     *
     * @param wzProgramUser
     */
    @Override
    public boolean updateUserInformation(WzProgramUser wzProgramUser) {
       WzProgramUser user = this.getById(wzProgramUser.getId());
       //用户等级
       if (ObjectUtils.isNotEmpty(wzProgramUser.getUserLevel())){
         user.setUserLevel(wzProgramUser.getUserLevel());
       }
       //用户名称
        if (ObjectUtils.isNotEmpty(wzProgramUser.getUserName())){
        user.setUserName(wzProgramUser.getUserName());
        }
        //手机号码
        if (ObjectUtils.isNotEmpty(wzProgramUser.getPhone())){
          user.setPhone(wzProgramUser.getPhone());
        }
        //所在位置
        if (ObjectUtils.isNotEmpty(wzProgramUser.getLocation())){
            user.setLocation(wzProgramUser.getLocation());
        }
        //红娘id
        if (ObjectUtils.isNotEmpty(wzProgramUser.getMatchmakerId())){
            user.setMatchmakerId(wzProgramUser.getMatchmakerId());
        }
        //友币
        if (ObjectUtils.isNotEmpty(wzProgramUser.getFriendc())){
        user.setFriendc(wzProgramUser.getFriendc());
        }
        //性别
        if(ObjectUtils.isNotEmpty(wzProgramUser.getSex())){
            user.setSex(wzProgramUser.getSex());
        }
        return this.updateById(user);
    }

    /**
     * 修改用户自我介绍
     *
     * @param wzUserDetails
     */
    @Override
    public boolean updateYourself(WzUserDetails wzUserDetails) {
        WzUserDetails wzUserDetails1 = wzUserDetailsService.selectWzUserDetailsById(wzUserDetails.getWid());
        wzUserDetails1.setIntroduce(wzUserDetails.getIntroduce());
        return wzUserDetailsService.updateById(wzUserDetails1);
    }

    /**
     * 删除用户
     *
     * @param ids
     */
    @Override
    public boolean batchDeletion(List<String> ids) {
        //删除用户信息
        this.removeByIds(ids);
        //删除用户详情
        wzUserDetailsService.deleteDetails(ids);
        return true;
    }

    /**
     * 修改支付宝账号
     *
     * @param wzProgramUser
     */
    @Override
    public boolean updateAlipay(WzUserDetails wzProgramUser) {
        WzUserDetails wzUserDetails1 = wzUserDetailsService.selectWzUserDetailsById(wzProgramUser.getWid());
        wzUserDetails1.setZfbAccount(wzProgramUser.getZfbAccount()); //支付宝账号
        wzUserDetails1.setZfbName(wzProgramUser.getZfbName()); //支付宝姓名
        return wzUserDetailsService.updateById(wzUserDetails1);
    }

    /**
     * 查询用户附近的人
     *
     * @param id
     */
    @Override
    public List<WzProgramUser> nearbyList(Long id) {
      WzProgramUser user =  this.getById(id); //查询用户信息
        return wzProgramUserMapper.nearbyList(user);
    }

//    /**
//     * 新增用户
//     *
//     * @param wzProgramUser
//     */
//    @Override
//    public boolean addUser(WzProgramUser wzProgramUser) {
//
//        //查询用户所在地经纬度
//        String location = TheMapApi.getLatAndLngByAddr(wzProgramUser.getLocation());
//        String longitude = location.substring(0,location.indexOf(","));//经度
//        String latitude =location.substring(longitude.length()+1,location.length()); //维度
//         wzProgramUser.setLongitude(longitude);
//         wzProgramUser.setLatitude(latitude);
//         wzProgramUser.setId(Long.parseLong(IdUtils.get16UUID(""))); //用户id
//        //判断是否携带邀请码
//        if (ObjectUtils.isNotEmpty(wzProgramUser.getInviterId())){
//           WzProgramUser inviterUser =this.getById(wzProgramUser.getInviterId());//邀请人
//            inviterUser.setFriendc(inviterUser.getFriendc()+10); //增加10友币
//            //给邀请人加友币
//            WzBalanceChangeRecord wzBalanceChangeRecord =new WzBalanceChangeRecord();
//            wzBalanceChangeRecord.setWid(inviterUser.getId()); //用户id
//            wzBalanceChangeRecord.setChangeMoney(10D); //变动金额
//            wzBalanceChangeRecord.setBalance(inviterUser.getFriendc().doubleValue()); //余额
//            wzBalanceChangeRecord.setCreateTime(new Date()); //创建时间
//            wzBalanceChangeRecord.setNote("邀请好友收益"); //备注
//            wzBalanceChangeRecord.setWname(inviterUser.getUserName()); //用户姓名
//            wzBalanceChangeRecord.setType(15); //类型
//            wzBalanceChangeRecord.setSourceId(wzProgramUser.getId()); //收益来源用户id
//            wzBalanceChangeRecord.setEarningsSource(wzProgramUser.getUserName()); //收益来源用户姓名
//            wzBalanceChangeRecord.setCommission(inviterUser.getCarryCommission()); //佣金
//            wzBalanceChangeRecordService.save(wzBalanceChangeRecord);
//            //判断团队红娘
//            if (ObjectUtils.isNotEmpty(inviterUser.getMatchmakerId())){
//                wzProgramUser.setMatchmakerId(inviterUser.getMatchmakerId());
//            }
//        }
//        return this.save(wzProgramUser);
//    }

    /**
     * 查询首页展示数据
     */
    @Override
    public Map<String, Object> homePageData() {
        Map<String,Object> map =new HashMap<>();
        //查询全部用户
        map.put("allUser",this.list().size());
        //新增付费会员
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getUserLevel,"2");
        lqw.between(WzProgramUser::getCreateTime, DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
         map.put("payMembers",this.list(lqw).size());
         //邀约订单
        map.put("invitationOrder",wzOrderService.invitationOrder().size());
         //交易金额
        map.put("sumMoney",wzOrderService.sumMoney());
        /*新增红娘申请*/
        //未处理申请
        WzMatchmakerApply wzMatchmakerApply =  new WzMatchmakerApply();
        wzMatchmakerApply.setStatus("0");
        map.put("untreated", wzMatchmakerApplyService.selectWzMatchmakerApplyList(wzMatchmakerApply).size());
       //已审核红娘申请
        wzMatchmakerApply.setStatus("1");
        map.put("checked", wzMatchmakerApplyService.selectWzMatchmakerApplyList(wzMatchmakerApply).size());
        //团队总人数
        LambdaQueryWrapper<WzProgramUser> lqw1 =new LambdaQueryWrapper<>();
        lqw1.isNotNull(WzProgramUser::getMatchmakerId);
        map.put("teamSum",this.list(lqw1).size());
        //新增团队人数
        lqw1.between(WzProgramUser::getCreateTime,DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
        map.put("addTeamMembers",this.list(lqw1).size());
        //取消红娘数
         map.put("cancelMatchmaker",wzMatchmakerApplyService.cancelMatchmakerList().size());
        /*新增约见订单*/
       //未处理约见订单
        WzOrder wzOrder =new WzOrder();
        wzOrder.setState("3");
        map.put("untreatedOrder", wzOrderService.invitationOrder(wzOrder).size());
        //约见成功订单
        wzOrder.setState("1");
       List<WzOrder> succeedOrder =  wzOrderService.invitationOrder(wzOrder);
        map.put("succeedOrder", succeedOrder.size() );
        //约见失败订单
        wzOrder.setState("2");
        map.put("failureOrder",wzOrderService.invitationOrder(wzOrder).size());
        //约见订单总金额
         wzOrder.setState(null);
        List<WzOrder> list = wzOrderService.invitationOrder(wzOrder);
        int orderAmount =0;
        if (ObjectUtils.isNotEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                orderAmount += list.get(i).getPayFriendc();
            }
        }
        map.put("orderAmount",orderAmount);
        //成功订单金额
        int succeedOrderAmount =0;
        if (ObjectUtils.isNotEmpty(succeedOrder)){
            for (int i = 0; i < succeedOrder.size(); i++) {
                succeedOrderAmount +=succeedOrder.get(i).getPayFriendc();
            }
        }
        map.put("succeedOrderAmount",succeedOrderAmount);
        /*佣金订单提现订单*/
        //新增佣金提现
        map.put("orderToday", wzWithdrawalRecordService.orderToday().size());
        //未处理提现
        QueryVo queryVo = new QueryVo();
        queryVo.setWithdrawalState("1");
       List<WzWithdrawalRecord>  untreatedReflectList = wzWithdrawalRecordService.selectWzWithdrawalRecordList(queryVo);
        map.put("untreatedReflect", untreatedReflectList.size());
        //待打款金额
        int noMoney =0;
        if(ObjectUtils.isNotEmpty(untreatedReflectList)){
            for (int i = 0; i < untreatedReflectList.size(); i++) {
                noMoney +=untreatedReflectList.get(i).getMoney();
            }
        }
       map.put("noMoney",noMoney);
        //已打款金额
        queryVo.setWithdrawalState("0");
        List<WzWithdrawalRecord>  yesMoneyList = wzWithdrawalRecordService.selectWzWithdrawalRecordList(queryVo);
        int yesMoney =0;
        if (ObjectUtils.isNotEmpty(yesMoneyList)){
            for (int i = 0; i < yesMoneyList.size(); i++) {
                yesMoney += yesMoneyList.get(i).getMoney();
            }
        }
      map.put("yesMoney",yesMoney);
        //已驳回打款金额
       int rejectedMoney =0;
        queryVo.setWithdrawalState("2");
        List<WzWithdrawalRecord>  rejectedMoneyList = wzWithdrawalRecordService.selectWzWithdrawalRecordList(queryVo);
        if (ObjectUtils.isNotEmpty(rejectedMoneyList)){
            for (int i = 0; i < rejectedMoneyList.size(); i++) {
                rejectedMoney +=rejectedMoneyList.get(i).getMoney();
            }
        }
      map.put("rejectedMoney",rejectedMoney);
        return map;
    }

    @Override
    public WzProgramUser getByPhone(Long phone) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getPhone,phone);
        return this.getOne(lqw);
    }

    /**
     * 修改用户在线状态
     *
     * @param wzProgramUser
     */
    @Override
    public boolean onlineStatus(WzProgramUser wzProgramUser) {
      WzProgramUser user = this.getById(wzProgramUser.getId());
      user.setOnlineStatus(wzProgramUser.getOnlineStatus()); //用户在线状态
        return this.updateById(user);
    }

    /**
     * 查看用户消息记录
     *
     * @param id
     */
    @Override
    public List<Object> informationRecord(Long id) {
        //查看评论记录
       LambdaQueryWrapper<WzComment> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzComment::getWid,id);
        lqw.isNotNull(WzComment::getCid);
        lqw.orderByDesc(WzComment::getCreateTime);
        List<WzComment> list =wzCommentsService.list(lqw);
        if (ObjectUtils.isNotEmpty(list)){
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setUser(wzProgramUserMapper.detailedProgramUser(list.get(i).getCid()));
            }
        }
        //查看关注列表
       List<WzFocuson> list1 = wzFocusonService.beAttention(id);
        List<Object> objectList =new ArrayList<>();
        if (ObjectUtils.isNotEmpty(list)){
            objectList.add(list);
        }
        if (ObjectUtils.isNotEmpty(list1)){
            objectList.add(list1);
        }
        System.out.println("排序前:"+objectList);
        if (ObjectUtils.isNotEmpty(objectList)){
            Collections.sort(objectList,new Comparator<Object>(){
                Map<String, Object> map01 = new HashMap<String, Object>();
                Map<String, Object> map02 = new HashMap<String, Object>();
                @Override
                public int compare(Object o1, Object o2) {
                    map01 = (Map<String, Object>) o1;
                    map02 = (Map<String, Object>) o2;
                    String value1 = (String) map01.get("endTime");
                    String value2 = (String) map02.get("endTime");
                    return value2.compareTo(value1);
                }
            });
        }

        System.out.println("排序后:"+objectList);

        return objectList;
    }

    /**查看我的团队用户列表*/
    @Override
    public List<WzProgramUser> myTeam(Long id,String type) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getInviterId,id);
        if (ObjectUtils.isNotEmpty(type)){
            switch (type){
                case "1" : //普通用户
                    lqw.eq(WzProgramUser::getRole,"1");
                    break;
                case "2": //会员用户
                    lqw.eq(WzProgramUser::getRole,"2");
                    break;
            }
        }
       List<WzProgramUser> list = this.list(lqw);
        return list;
    }

    /**
     * 查看团队营收
     *
     * @param id
     */
    @Override
    public Map<String, Object> teamReceivable(Long id) {
        Map<String,Object> map =new HashMap<>();
        //查看团队用户
        List<WzProgramUser> teamUser =this.myTeam(id,null);
        List<Long> ids =new ArrayList<>();
        for (int i = 0; i < teamUser.size(); i++) {
            ids.add(teamUser.get(i).getId());
        }
        //查询今日团队总营收
        LambdaQueryWrapper<WzBalanceChangeRecord> lqw =new LambdaQueryWrapper<>();
        lqw.in(WzBalanceChangeRecord::getType,"1","2","3","4","5","6");
        lqw.in(WzBalanceChangeRecord::getWid,ids);
        lqw.between(WzBalanceChangeRecord::getCreateTime,DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
        List<WzBalanceChangeRecord> receivableList = wzBalanceChangeRecordService.list(lqw);
        Double receivableMoney =0D;
        if (ObjectUtils.isNotEmpty(receivableList)){
            for (int i = 0; i < receivableList.size(); i++) {
                receivableMoney += receivableList.get(i).getChangeMoney();
            }
        }
        map.put("receivableMoney",receivableMoney); //团队今日营收
        //查询昨日团队总营收
        LambdaQueryWrapper<WzBalanceChangeRecord> lqwYesterday =new LambdaQueryWrapper<>();
        lqwYesterday.in(WzBalanceChangeRecord::getType,"1","2","3","4","5","6");
        lqwYesterday.in(WzBalanceChangeRecord::getWid,ids);
        lqwYesterday.between(WzBalanceChangeRecord::getCreateTime,DateUtils.DateToString(DateUtils.reductionTime(new Date(),1)),DateUtils.DateToString(new Date()));
        List<WzBalanceChangeRecord> yesterdayList = wzBalanceChangeRecordService.list(lqwYesterday);
        Double yesterdayMoney =0D;
        if (ObjectUtils.isNotEmpty(yesterdayList)){
            for (int i = 0; i < yesterdayList.size(); i++) {
                yesterdayMoney +=yesterdayList.get(i).getChangeMoney();
            }
        }
        map.put("yesterdayMoney",yesterdayMoney); //昨日团队营收
        //查询今日归属红娘收益
        LambdaQueryWrapper<WzBalanceChangeRecord> todayMatchmaker =new LambdaQueryWrapper<>();
        todayMatchmaker.in(WzBalanceChangeRecord::getType,"1","2","3","4","5","6");
        todayMatchmaker.in(WzBalanceChangeRecord::getWid,id);
        todayMatchmaker.between(WzBalanceChangeRecord::getCreateTime,DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.reductionTime(new Date(),1)));
        List<WzBalanceChangeRecord> todayMatchmakerList = wzBalanceChangeRecordService.list(todayMatchmaker);
        Double todayMatchmakerMoney=0D;
        if (ObjectUtils.isNotEmpty(todayMatchmakerList)){
            for (int i = 0; i < todayMatchmakerList.size(); i++) {
                todayMatchmakerMoney +=todayMatchmakerList.get(i).getChangeMoney();
            }
        }
        map.put("todayMatchmakerMoney",todayMatchmakerMoney); //今日红娘收益
        //查询昨日红娘收益
        LambdaQueryWrapper<WzBalanceChangeRecord> yesterdayMatchmaker =new LambdaQueryWrapper<>();
        yesterdayMatchmaker.in(WzBalanceChangeRecord::getType,"1","2","3","4","5","6");
        yesterdayMatchmaker.in(WzBalanceChangeRecord::getWid,id);
        yesterdayMatchmaker.between(WzBalanceChangeRecord::getCreateTime,DateUtils.DateToString(DateUtils.reductionTime(new Date(),1)),DateUtils.DateToString(new Date()));
        List<WzBalanceChangeRecord> yesterdayMatchmakerMatchmakerList = wzBalanceChangeRecordService.list(yesterdayMatchmaker);
        Double yesterdayMatchmakerMoney=0D;
        if (ObjectUtils.isNotEmpty(yesterdayMatchmakerMatchmakerList)){
            for (int i = 0; i < yesterdayMatchmakerMatchmakerList.size(); i++) {
                yesterdayMatchmakerMoney +=yesterdayMatchmakerMatchmakerList.get(i).getChangeMoney();
            }
        }
        map.put("yesterdayMatchmakerMoney",yesterdayMatchmakerMoney); //昨日红娘收益
        return map;
    }

    /**
     * 查看团队邀请信息
     *
     * @param id
     */
    @Override
    public List<WzProgramUser> invitationRecord(Long id,String state) {
        //查看团队列表
        List<WzProgramUser> userList =  this.myTeam(id,null);
        List<Long> ids =new ArrayList<>();
        if (ObjectUtils.isNotEmpty(userList)){
            for (int i = 0; i < userList.size(); i++) {
                ids.add(userList.get(i).getId());
            }
        }
        if (ObjectUtils.isEmpty(ids)){
            return userList;
        }
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.in(WzProgramUser::getId,ids);
       List<WzProgramUser> list = this.list(lqw);
       if (ObjectUtils.isNotEmpty(list)){
           for (int i = 0; i < list.size(); i++) {
               if (ObjectUtils.isNotEmpty(state)){
                   list.get(i).setInvitationQuantity(seeInvitationQuantity(list.get(i).getId(),state));
               }else{
                   list.get(i).setInvitationQuantity(seeInvitationQuantity(list.get(i).getId(),null));
               }
           }
       }
        return list;
    }

    /**
     * 查看用户列表
     * type 0-女用户  1-男用户
     *返回用户列表id
     * @param type
     */
    @Override
    public List<Long> getByType(String type) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        if (type.equals("0")){
            lqw.eq(WzProgramUser::getSex,"2");
        }else if (type.equals("1")){
            lqw.eq(WzProgramUser::getSex,"1");
        }
       List<WzProgramUser> list = this.list(lqw);
        List<Long> ids =new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ids.add(list.get(i).getId());
        }
        return  ids;
    }

    /**
     * 开通免费会员
     *
     * @param wzProgramUser
     */
    @Override
    public boolean freeMembership(WzProgramUser wzProgramUser) {
          WzProgramUser user = this.getById(wzProgramUser.getId());
          user.setRole("2");
          user.setUserLevel("2");
          user.setFreeMembership("1");
          String key ="KTHY"+user.getId();
        redisCache.setCacheObject(key,key,3, TimeUnit.DAYS);
        return this.updateById(user);
    }

    @Override
    public List<WzProgramUser> getByMatchmakerId(Long id) {
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getMatchmakerId,id);
        return this.list(lqw);
    }

    /**
     * 用户充值友币
     *
     * @param wzPayOrderRecord
     */
    @Override
    public boolean topUp(WzPayOrderRecord wzPayOrderRecord) {
        if (ObjectUtils.isNotEmpty(wzPayOrderRecord)){
            wzPayOrderRecord.setState("1"); //订单状态已支付
            wzPayOrderRecord.setPayTime(new Date()); //支付成功时间
            wzPayOrderRecordService.updateById(wzPayOrderRecord);
            //给用户账号充值友币
            //添加用户余额变更记录
            WzBalanceChangeRecord wzBalanceChangeRecord =new WzBalanceChangeRecord();
            WzProgramUser user = this.getById(wzPayOrderRecord.getWid());
            wzBalanceChangeRecord.setBalance(user.getFriendc().doubleValue()); //余额
            user.setFriendc(user.getFriendc() + wzPayOrderRecord.getFriend());
            wzBalanceChangeRecord.setWid(user.getId()); //用户id
            wzBalanceChangeRecord.setChangeMoney(wzPayOrderRecord.getFriend().doubleValue()); //变动金额
            wzBalanceChangeRecord.setCreateTime(new Date()); //创建时间
            wzBalanceChangeRecord.setWname(user.getUserName()); //用户名称
            wzBalanceChangeRecord.setNote("友币充值"); //备注
            wzBalanceChangeRecord.setType(14); //订单类型
            wzBalanceChangeRecord.setOrderNumber(wzPayOrderRecord.getOrderSn()); //订单号
            wzBalanceChangeRecordService.save(wzBalanceChangeRecord);
            this.updateById(user);
            return true;
        }
        return false;
    }

    /**查看用户邀请人数*/
    public int seeInvitationQuantity(Long id,String state){
        LambdaQueryWrapper<WzProgramUser> lqw =new LambdaQueryWrapper<>();
        lqw.eq(WzProgramUser::getInviterId,id);
        if (ObjectUtils.isNotEmpty(state)){
            if (state.equals("1")){//今日邀请人数
            lqw.between(WzProgramUser::getSubordinateTime,DateUtils.DateToString(new Date()),DateUtils.DateToString(DateUtils.addTime(new Date(),1)));
           return this.list(lqw).size();
            }else{ //查询本月邀请人数
                lqw.between(WzProgramUser::getSubordinateTime,DateUtils.monthFirstDay(),DateUtils.monthLastDay());
              return this.list(lqw).size();
            }
        }
        return this.list(lqw).size();
    }


}


